package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.esotericsoftware.minlog.Log;
import com.ndp.ec.core.UserService;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.exception.ResourceNotificationMsgManager;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.redis.api.RedisDistributedLockService;
import com.ndp.fb.walle.business.EventNotificationService;
import com.ndp.fb.walle.business.MessageService;
import com.ndp.fb.model.business.vo.BaseVoParam;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.model.vo.eventnotificationmessage.EventNotificationMessageVo;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by evan.wan on 2015/7/31.
 */
@RequestMapping("/notice")
@Controller
public class EventNotificationController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private EventNotificationService eventNotificationService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private RedisDistributedLockService redisDistributedLockService;

    @Reference
    private UserService userManager;


    /**
     * 根据用户 查询所有消息
     * @param request
     * @return
     */
    @RequestMapping(value = "getNotice")
    @ResponseBody
    public ResponseEntity<String> getNotice(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("EventNotificationController getNotice() begin.");
        ErrorType errorType = null;
        Map<String, Object> data = null;

        try {
            User user = (User) request.getSession().getAttribute("user");
            BaseVoParam baseVoParam = JSON.parseObject(param, BaseVoParam.class);

            // 查询列表
            Integer sizeNo = baseVoParam.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : baseVoParam
                    .getPSize();
            Integer firstResult = baseVoParam.getCPage() == null ? 0 : (baseVoParam.getCPage() - 1) * sizeNo;

            Pager<EventNotificationMessageVo> listBo = messageService.findUnReadEventNotificationMessageByUserId(user.getTicket(), firstResult, sizeNo);

            List<EventNotificationMessageVo> resultList = listBo.getResultList();
            if (null == listBo || null == resultList || null == listBo.getTotalSize()) {
                data = new HashMap<>();
                data.put("notice", "");
            } else {
                // 计算分页结果
                long tSize = listBo.getTotalSize();
                float nrOfPages = (float) tSize / sizeNo;
                int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
                PageResult pageResult = new PageResult(tPage, baseVoParam.getCPage(), baseVoParam.getPSize(), tSize);

                for (EventNotificationMessageVo eventNotificationMessageVo : resultList) {
                    String eventValues = eventNotificationMessageVo.getEventValues();
                    String language = user.getLanguage();
                    String eventKey = eventNotificationMessageVo.getEventKey();
                    String body = ResourceNotificationMsgManager.getNotificationResource(language,eventKey,eventValues);
                    eventNotificationMessageVo.setBody(body);
                    if (ResourceNotificationMsgManager.isCN(language)) {
                        eventNotificationMessageVo.setTitle(eventNotificationMessageVo.getEventType().getName());
                    } else {
                        eventNotificationMessageVo.setTitle(eventNotificationMessageVo.getEventType().getEnName());
                    }
                }
                // 封装响应结果
                data = new HashMap<>();
                data.put("notice", resultList);
                data.put("paginator", pageResult);
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("EventNotificationController getNotice() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 查询事件通知列表
     * @param request
     * @return
     */
    @RequestMapping(value = "getMessages")
    @ResponseBody
    public ResponseEntity<String> getEventMessage(HttpServletRequest request) {
        ErrorType errorType = null;
        User user =  (User) request.getSession().getAttribute("user");
        Pager<EventNotificationMessageVo> pager = messageService.findUnReadEventNotificationMessageByUserId(user.getTicket(), 0, 1000);
        String language = user.getLanguage();
        for (EventNotificationMessageVo eventNotificationMessageVo : pager.getResultList()) {
            String eventKey = eventNotificationMessageVo.getEventKey();
            String eventValues = eventNotificationMessageVo.getEventValues();
            String body = ResourceNotificationMsgManager.getNotificationResource(language,eventKey,eventValues);
            eventNotificationMessageVo.setBody(body);
            if (ResourceNotificationMsgManager.isCN(language)) {
                eventNotificationMessageVo.setTitle(eventNotificationMessageVo.getEventType().getName());
            } else {
                eventNotificationMessageVo.setTitle(eventNotificationMessageVo.getEventType().getEnName());
            }
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, pager);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 更新消息-将消息标为已读
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "updateMessage")
    @ResponseBody
    public ResponseEntity<String> updateMessage(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        String id = JSON.parseObject(param).getString("id");
        User user =  (User) request.getSession().getAttribute("user");
        Long l = 0l;
        try {
            if (redisDistributedLockService.tryLock(CommonConstants.BADAGE_NUM_LOCK + user.getTicket(), 1, TimeUnit.MINUTES)) {
                user = userManager.findByUsername(user.getUsername());
                if (user.getBadgeNum() - 1 >= 0) {
                    user.setBadgeNum(user.getBadgeNum() - 1);
                }
                userManager.update(user);
                l = messageService.updateReadStatusById(id);
            }
        } catch (Exception ex) {
            Log.error(ex.getMessage(), ex);
        } finally {
            redisDistributedLockService.unLock(CommonConstants.BADAGE_NUM_LOCK + user.getTicket());
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, l);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 删除消息
     * @return
     */
    @RequestMapping(value = "delNotice")
    @ResponseBody
    public ResponseEntity<String> delNotice(@RequestParam(value = "param", required = true) String param) {
        logger.info("EventNotificationController delNotice() begin.");
        ErrorType errorType = null;
        BaseVoParam baseVoParam = JSON.parseObject(param, BaseVoParam.class);
        if(baseVoParam == null || baseVoParam.getId() == null)
            errorType = ErrorType.PARAM_EXCEPTION;
        eventNotificationService.delById(baseVoParam.getId());
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, null);
        logger.info("EventNotificationController delNotice() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
}
